#include <unistd.h>
#include <sys/wait.h>
#include <iostream>
#include <string>
#include <vector>
int lsh_launch(std::vector<std::string>& args)
{
  int status;
  std::vector<char*> argv;
  for (auto& arg : args) {
    argv.push_back(&arg[0]);
  }
  argv.push_back(nullptr);  // execvp要求数组以nullptr结尾
  pid_t pid = fork();
  if (pid == 0) {
    // Child process
    if (execvp(argv[0], argv.data()) == -1) {  // 使用转换后的argv
      perror("lsh");
    }
    exit(1);
  } else if (pid < 0) {
    // Error forking
    perror("lsh");
  } else {
    // Parent process
    do {
      waitpid(pid, &status, WUNTRACED);
    } while (!WIFEXITED(status) && !WIFSIGNALED(status));
  }
  return 1;
}
void lsh_split(const std::string& s, std::vector<std::string>& tokens, const std::string& delimiters = " ")
{
    std::string::size_type lastPos = s.find_first_not_of(delimiters, 0);
    std::string::size_type pos = s.find_first_of(delimiters, lastPos);
    while (std::string::npos != pos || std::string::npos != lastPos) {
        tokens.push_back(s.substr(lastPos, pos - lastPos));//use emplace_back after C++1
        lastPos = s.find_first_not_of(delimiters, pos);
        pos = s.find_first_of(delimiters, lastPos);
    }
}
void lsh_loop(){
    int status;
    do{
        std::string command;
        std::vector<std::string> args;
        printf(">");
        std::getline(std::cin, command);
        lsh_split(command, args);
        status = lsh_launch(args);
    }while(status);
}
int main()
{
    lsh_loop();
    return 0;
}